package com.gitee.fsmxm.thinking.in.concurrent.basic;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 线程池
 * <p>不推荐使用Executors创建线程池
 * <p>推荐使用有界任务队列
 * <p>推荐自定义ThreadFactory
 * <p>推荐自定义拒绝策略
 */
public class _10_ThreadPool_Executor {

    public static class MyThreadFactory implements ThreadFactory {
        private final String namePrefix;
        private final AtomicLong index;
        public MyThreadFactory(String namePrefix) {
            this.namePrefix = namePrefix;
            index = new AtomicLong(0);
        }
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName(namePrefix + "-" + index.getAndIncrement());
            return thread;
        }
    }

    public static class MyRejectExecutionHandler implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            // do ...
        }
    }

    public static void main(String[] args) {
        new ThreadPoolExecutor(2,
                5,
                60L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(20),
                new MyThreadFactory("T"),
                new MyRejectExecutionHandler());
    }

}
